package com.application;

import com.audio.AudioPlayer;
import com.entiy.Sentences;
import com.http.TTSHttpClient;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TTSAudio {
    private static volatile boolean isRunning = true;

    public TTSAudio() {
        try {
            // 初始化组件
            Sentences sentences = Sentences.getInstance(); // 使用单例实例
            TTSHttpClient client = new TTSHttpClient("http://127.0.0.1:8000");
            AudioPlayer audioPlayer = new AudioPlayer();

            // 启动守护线程
            Thread playerThread = new Thread(audioPlayer);
            playerThread.setDaemon(true);
            playerThread.start();

            // 创建监听执行器
            ExecutorService monitorExecutor = Executors.newSingleThreadExecutor();
            monitorExecutor.submit(() -> processSentences(sentences, client, audioPlayer));

            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                isRunning = false;
                monitorExecutor.shutdownNow();
                //audioPlayer.stopAndClear();
            }));

            // 保持主线程运行
            while (isRunning) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void processSentences(Sentences sentences,
                                         TTSHttpClient client,
                                         AudioPlayer audioPlayer) {
        while (isRunning && !Thread.currentThread().isInterrupted()) {
            try {
                // 阻塞式获取句子（最长等待5秒）
                String sentence = sentences.getSentenceQueue().poll(5, TimeUnit.SECONDS);
                if (sentence == null) continue;

                //System.out.println("\n收到新句子: " + sentence);

                // 生成音频文件
                String outputFile = generateAudio(client, sentence);

                // 加入播放队列
                audioPlayer.addToQueue(outputFile);
                //System.out.println("已加入播放队列: " + outputFile);

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                System.err.println("处理失败: " + e.getMessage());
            }
        }
    }

    private static String generateAudio(TTSHttpClient client, String text) throws Exception {
        Map<String, Object> payload = new HashMap<>();
        payload.put("text", text);
        payload.put("gender", "female");
        payload.put("pitch", 5);
        payload.put("speed", 4);
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        payload.put("save_path", "F:/develop/item/voice/file/1/test/"+timestamp+".wav");

        return client.textToSpeech(payload);
    }
}